package com.yunchen.server.configure;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.context.SaHolder;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    
    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验
		registry.addInterceptor(new SaInterceptor(handle -> {
			// 预检请求不做登录校验，避免拦截 CORS 预检
			if ("OPTIONS".equalsIgnoreCase(SaHolder.getRequest().getMethod())) {
				return;
			}
			// 检查登录状态，如果未登录会抛出NotLoginException
			StpUtil.checkLogin();
		}))
        .addPathPatterns("/**")
        .excludePathPatterns(
            "/Users/Login",     // 登录接口
            "/Users/Logout"   // 登出接口
        ); 
    }

	// 全局跨域配置
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
			.allowedOriginPatterns("*")
			.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD")
			.allowedHeaders("*")
			.exposedHeaders("*")
			.allowCredentials(true)
			.maxAge(3600);
	}
}
